const http = require("http");
const url = require("url");
const fs = require('fs');

const sleep = function (time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
}

const router = {
    "/m1": async function (req, res) {
        await sleep(3000);
        res.end("m1");
    },
    "/m2": async function (req, res) {
        await sleep(2000);
        res.end("m1");
    },
}

function route(pathname, req, res) {
    let r = router[pathname];
    if (typeof r === 'function') {
        r(req, res);
    } else if(pathname.endsWith("html")){
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.end(fs.readFileSync("."+pathname));
    }else{
        res.end();
    }
}

function onRequest(request, response) {
    const pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    route(pathname, request, response);
    // response.writeHead(200, { "Content-Type": "text/plain" });
    // response.write("Hello World");
    // response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started.");